<template>
	<view>
		<view
			class="record-btn"
			@click="startRecord"
			hover-start-time="200"
			hover-stay-time="150"
			:style="[btnStyle]"
		>
			<view
				class="voice-line-wrap"
				v-if="recording"
				:style="{ '--line-height': upx2px(lineHeight), '--line-start-color': lineStartColor, '--line-end-color': lineEndColor }"
			>
				<view class="voice-line one"></view>
				<view class="voice-line two"></view>
				<view class="voice-line three"></view>
				<view class="voice-line four"></view>
				<view class="voice-line five"></view>
				<view class="voice-line six"></view>
				<view class="voice-line seven"></view>
				<view class="voice-line six"></view>
				<view class="voice-line five"></view>
				<view class="voice-line four"></view>
				<view class="voice-line three"></view>
				<view class="voice-line two"></view>
				<view class="voice-line one"></view>
			</view>
			<view
				class="voice-line-wrap2"
				v-if="recording"
				:style="{ '--line-height': upx2px(lineHeight), '--line-start-color': lineStartColor, '--line-end-color': lineEndColor }"
			>
				<view class="voice-line one"></view>
				<view class="voice-line two"></view>
				<view class="voice-line three"></view>
				<view class="voice-line four"></view>
				<view class="voice-line five"></view>
				<view class="voice-line six"></view>
				<view class="voice-line seven"></view>
				<view class="voice-line six"></view>
				<view class="voice-line five"></view>
				<view class="voice-line four"></view>
				<view class="voice-line three"></view>
				<view class="voice-line two"></view>
				<view class="voice-line one"></view>
			</view>
			<view v-if="recording" style="position: relative; width: 100%; height: 100%;">
				<l-circle :percent="current" :max="60" size="100rpx" strokeWidth="3" strokeColor="#00c386" trailWidth="3" trailColor="#ffffff">
				    <view style="width: 35rpx; height: 35rpx; border-radius: 10rpx; background-color: #00c386;"></view>
				</l-circle>
				<!-- <c_circle class="mine-member-level-progress" :diameter="180" :hoopThickness="10" :hoopColor="'orange'" :percent="current" :animate="true" /> -->
			</view>
			<template v-else>
				<uni-icons type="mic-filled" size="52rpx" class="flex items-center" color="#00c386"></uni-icons>
			</template>
		</view>
	</view>
</template>
<script>
// #ifdef APP-PLUS
import permision from '../lib/permission.js';
// const plug = uni.requireNativePlugin("html5app-recordaudio")
// #endif
// import c_circle from './circle.vue'
export default {
	name: 'nbVoiceRecord',
	// components: {c_circle},
	/**
	 * 录音交互动效组件
	 * @property {Object} recordOptions 录音配置
	 * @property {Object} btnStyle 按钮样式
	 * @property {String} btnDefaultText 按钮初始文字
	 * @property {String} btnRecordingText 录制时按钮文字
	 * @property {Boolean} vibrate 弹窗时是否震动
	 * @property {String} popupTitle 弹窗顶部文字
	 * @property {String} popupDefaultTips 录制时弹窗底部提示
	 * @property {String} popupCancelTips 滑动取消时弹窗底部提示
	 * @property {String} popupMaxWidth 弹窗展开后宽度
	 * @property {String} popupMaxHeight 弹窗展开后高度
	 * @property {String} popupFixBottom 弹窗展开后距底部高度
	 * @property {String} popupBgColor 弹窗背景颜色
	 * @property {String} lineHeight 声波高度
	 * @property {String} lineStartColor 声波波谷时颜色色值
	 * @property {String} lineEndColor 声波波峰时颜色色值
	 * @event {Function} startRecord 开始录音回调
	 * @event {Function} endRecord 结束录音回调
	 * @event {Function} cancelRecord 滑动取消录音回调
	 * @event {Function} stopRecord 主动停止录音
	 */
	props: {
		recordOptions: {
			type: Object,
			default() {
				return {
					duration: 600000
				}; // 请自行查看各端的的支持情况，这里全部使用默认配置
			}
		},
		btnStyle: {
			type: Object,
			default() {
				return {
					height: '100rpx',
					width: '100rpx'
				};
			}
		},
		vibrate: {
			type: Boolean,
			default: true
		},
		lineHeight: {
			type: Number,
			default: 25 // 单位为rpx
		},
		lineStartColor: {
			type: String,
			default: '#00c386' // 颜色名称或16进制色值
		},
		lineEndColor: {
			type: String,
			default: '#00c386' // 颜色名称或16进制色值
		}
	},
	data() {
		return {
			stopStatus: false, // 是否已被父页面通知主动结束录音
			startTouchData: {},
			recording: false, // 录音中
			recordTimeout: null, // 录音定时器
			current: 0,
			timer: null,
			recorderManager: null
			
		};
	},
	created() {
		// #ifdef APP
		this.checkPermission()
		// #endif
		
		this.recorderManager = uni.getRecorderManager()
		
		this.recorderManager.onStop((res) => {
			if (this.recordTimeout !== null) {
				clearTimeout(this.recordTimeout);
				this.recordTimeout = null;
			}
			this.recording = false
			this.$emit('endRecord', res);
		})
		
		this.recorderManager.onStart(() => {
			this.recording = true
			this.timer = setInterval(() => {
				this.current = parseInt(this.current + 1)
				console.log(this.current)
				if(this.current === 60){
					this.stopRecord(); // 结束录音动画（实际上录音的end回调已经先执行）
					this.recordTimeout = null; // 重置
					clearInterval(this.timer)
					this.current = 0
				}
			}, 1000)
			this.$emit('startRecord');
		})

		this.recorderManager.onError(err => {
			if(err.errrMsg === 'operateRecorder:fail NotFoundError'){
				uni.showToast({ title: '本机暂无声卡，请重试',icon: 'none' })
			} else{
				uni.showToast({ title: '录音失败，请重试',icon: 'none' })
			}
		})
	},
	methods: {
		upx2px(upx) {
			return uni.upx2px(upx) + 'px';
		},
		async checkPermission() {
			// #ifdef APP-PLUS
			// 先判断os
			let os = uni.getSystemInfoSync().osName;
			if (os == 'ios') {
				this.permisionState = await permision.judgeIosPermission('record');
			} else {
				this.permisionState = await permision.requestAndroidPermission('android.permission.RECORD_AUDIO');
			}
			if (this.permisionState !== true && this.permisionState !== 1) {
				uni.showToast({
					title: '请先授权使用录音',
					icon: 'none'
				});
				return;
			}
			// #endif

			// #ifndef APP-PLUS
			let _this = this
			uni.authorize({
				scope: 'scope.record',
				success: (e) => {
					_this.permisionState = true;
					_this.startRecord();
				},
				fail: (err) => {
					console.log('调用录音权限错误', err)
					uni.showToast({
						title: '禁止答题，请授权使用录音',
						icon: 'none'
					});
					uni.openSetting({
						success(res) {
						    console.log(res.authSetting)
						}
					})
					
				}
			});
			// #endif
		},

		startRecord() {
			if (!this.permisionState) {
				this.checkPermission();
				return;
			}
			if(this.recording){
				this.endRecord()
			} else{
				if (this.vibrate) {
					// #ifdef APP-PLUS
					plus.device.vibrate(35);
					// #endif
					// #ifdef MP-WEIXIN
					uni.vibrateShort();
					// #endif
				}
				// 开始录音
				let os = uni.getSystemInfoSync().osName;
				if (os == 'android') {
					// plug.start({
					// 	format:"wav",
					// 	rate:16000,
					// 	encode:16,
					// 	channel: 1,
					// }, (e) => {
					// 	console.log(JSON.stringify(e));
					// 	this.recording = true
					// })
					this.recorderManager.start(this.recordOptions);
				} else {
					this.recorderManager.start(this.recordOptions);
				}
			}
		},
		endRecord() {
			if (this.stopStatus) {
				return;
			}
			let os = uni.getSystemInfoSync().osName;
			if (os == 'android') {
				// plug.stop(function(e){    
				//     console.log(e);
				// });
				this.recorderManager.stop();
			} else{
				this.recorderManager.stop();
			}
			clearInterval(this.timer)
			this.current = 0
			this.recording = false
		},
		stopRecord() {
			// 用法如你录音限制了时间，那么将在结束时强制停止组件的显示
			this.endRecord();
			this.stopStatus = true;
		}
	}
};
</script>
<style lang="scss">
.record-btn {
	color: #fff;
	font-size: 32rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	transition: 0.25s all;
	background-color: #fff;
	border-radius: 100%;
	position: relative;
	margin: 0 auto;
}

.record-btn-hover {
	// background-color: rgba(#2270fc, 1);
}

.record-popup {
	position: absolute;
	bottom: var(--popup-bottom);
	left: calc(50vw - calc(var(--popup-width) / 2));
	z-index: 1;
	width: var(--popup-width);
	height: var(--popup-height);
	display: flex;
	align-items: center;
	justify-content: center;
	border-radius: 10rpx;
	box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
	background: var(--popup-bg-color);
	color: #000;
	transition: 0.2s height;

	.inner-content {
		height: var(--popup-height);
		font-size: 24rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: space-between;

		.title {
			font-weight: bold;
			padding: 20rpx 0;
		}
		.tips {
			color: #999;
			padding: 20rpx 0;
		}
	}
}

.cancel-icon {
	width: 100rpx;
	height: 100rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	color: #fff;
	font-size: 44rpx;
	line-height: 44rpx;
	background-color: pink;
	border-radius: 50%;
	transform: rotate(45deg);
}

.voice-line-wrap {
	display: flex;
	align-items: center;
	position: absolute;
	left: -140rpx;
	.voice-line {
		width: 4rpx;
		height: var(--line-height);
		border-radius: 3rpx;
		margin: 0 2rpx;
	}

	.one {
		animation: wave 0.4s 1s linear infinite alternate;
	}
	.two {
		animation: wave 0.4s 0.9s linear infinite alternate;
	}
	.three {
		animation: wave 0.4s 0.8s linear infinite alternate;
	}
	.four {
		animation: wave 0.4s 0.7s linear infinite alternate;
	}
	.five {
		animation: wave 0.4s 0.6s linear infinite alternate;
	}
	.six {
		animation: wave 0.4s 0.5s linear infinite alternate;
	}
	.seven {
		animation: wave 0.4s linear infinite alternate;
	}
}
.voice-line-wrap2 {
	display: flex;
	align-items: center;
	position: absolute;
	right: -140rpx;
	.voice-line {
		width: 4rpx;
		height: var(--line-height);
		border-radius: 3rpx;
		margin: 0 2rpx;
	}

	.one {
		animation: wave 0.4s 1s linear infinite alternate;
	}
	.two {
		animation: wave 0.4s 0.9s linear infinite alternate;
	}
	.three {
		animation: wave 0.4s 0.8s linear infinite alternate;
	}
	.four {
		animation: wave 0.4s 0.7s linear infinite alternate;
	}
	.five {
		animation: wave 0.4s 0.6s linear infinite alternate;
	}
	.six {
		animation: wave 0.4s 0.5s linear infinite alternate;
	}
	.seven {
		animation: wave 0.4s linear infinite alternate;
	}
}

@keyframes wave {
	0% {
		transform: scale(1, 1);
		// background-color: var(--line-start-color);
		background-color: var(--line-start-color);
	}
	100% {
		transform: scale(1, 0.2);
		// background-color: #00c386;
		background-color: var(--line-end-color);
	}
}
</style>
